package com.zqx.strategy.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.web.bind.annotation.*;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

@RestController
public class UserController {

    private static final String utf8="utf-8";

    /**
     * 断点续传
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/upload")
    public void upload(HttpServletRequest request, HttpServletResponse response) throws Exception{
        //分片
        response.setCharacterEncoding(utf8);
        Integer schunk=null;
        Integer schunks=null;

        String name=null;
        String uploadPath = "F:\\fileItem";
        BufferedOutputStream os = null;

        try{
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setRepository(new File(uploadPath));
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setFileSizeMax(10L*1024L*1024L*1024L);
            upload.setSizeMax(10L*1024L*1024L*1024L);
            List<FileItem> fileItems = upload.parseRequest(request);
            for (FileItem item:fileItems
                    ) {
                if (item.isFormField()) {
                    if ("chunk".equals(item.getFieldName())) {
                        schunk = Integer.parseInt(item.getString(utf8));
                    }
                    if ("chunks".equals(item.getFieldName())) {
                        schunks = Integer.parseInt(item.getString(utf8));
                    }
                    if ("name".equals(item.getFieldName())) {
                        name = item.getString(utf8);
                    }
                }
            }

            for (FileItem item:fileItems) {
                if (!item.isFormField()) {
                    String temFileName = name;
                    if (name!=null) {
                        if (schunk!=null) {
                            temFileName=schunk+"_"+name;
                        }
                        File tempFile = new File(uploadPath);
                        if (!tempFile.exists()) {//断点续传 这两行是核心
                            item.write(tempFile);//断点续传
                        }
                    }
                }
            }
            //判断是否是最后的分片
            if (schunk!=null && schunk.intValue() == schunks.intValue()-1) {
                File tempFile = new File(uploadPath, name);
                os = new BufferedOutputStream(new FileOutputStream(tempFile));
                for (int i = 0; i < schunks; i++) {
                    File file = new File(uploadPath, i + "_" + name);
                    //为了确保高并发下文件完整
                    while (file.exists()){
                        Thread.sleep(100);
                    }
                    byte[] bytes = FileUtils.readFileToByteArray(file);
                    os.write(bytes);
                    os.flush();
                    file.delete();
                }
                os.flush();
            }
            response.getWriter().write("上传成功"+name);
        }finally {

        }
    }
}
